require 'plugins/list'
require 'ftools'

class Backup 
  def execute(source, args)
    if args.length == 0
      puts "please supply backup directory name"
    end
    backup_dir = args[0]
    search_key = args[1] ? args[1] : 'All tracks'
    puts "backing up to " + backup_dir + ", key: #{search_key}"

    lister = List.new
    nodes = lister.execute(source, [search_key])
    nodes_to_backup = get_nodes_to_backup(source, nodes)
    nodes_to_backup.each do |e| 
      dir = clean_path("#{backup_dir}/#{e.artist}/#{e.album}")
      File.makedirs(dir)
      raise "failed to create directory: #{dir}" if !File.exists?(dir)
      mp3_file = dir + clean_path("/#{e.trackno}-#{e.name}") + ".mp3"
      puts "#{e.url}  #{mp3_file}"
      #system("curl -retry 3 -o \'#{mp3_file}\' #{e.url}")

    end
  end
  
  private 
  private 
  def clean_path(path)
    path.gsub(/[ \?\'\!]+/, "_")
  end 
  
  def get_nodes_to_backup(source, top_level_nodes)
    return if top_level_nodes == nil || top_level_nodes.length == 0
    
    nodes_to_backup = []
    nodes_to_process = []
    
    top_level_nodes.each do |node|
      if !(node.name =~ /^All/)
        if node.url
          nodes_to_backup << node 
        else 
          source.get_children_of(node).each {|child_node| nodes_to_process << child_node }
        end
      end
    end
    more_nodes = get_nodes_to_backup(source, nodes_to_process) 
    nodes_to_backup = nodes_to_backup + more_nodes if more_nodes
    nodes_to_backup
  end
end